﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Managements.Devices;
using YAPACS.BusinessObjects.Services;
using YAPACS.Organizations;

namespace YAPACS.RisServer.Controllers;
[Authorize]
public class DeviceTypeController(
    IStationCodeProvider stationCodeProvider,
    IRepository<Department, Guid> departmentRepository,
    ICurrentUserOrganization currentUserOrganization,
    IRepository<DeviceType, Guid> deviceTypeRepository,
    IRepository<Station, Guid> stationRepository) : AbpController
{
    private readonly string stationCode = stationCodeProvider.GetStationCode();
    private readonly IRepository<DeviceType, Guid> _deviceTypeRepository = deviceTypeRepository;
    private readonly IRepository<Department, Guid> _departmentRepository = departmentRepository;
    private readonly ICurrentUserOrganization _currentUserOrganization = currentUserOrganization;
    private readonly IRepository<Station, Guid> _stationRepository = stationRepository;

    [HttpGet]
    [Route("api/get-device-types")]
    public async Task<IActionResult> GetDeviceTypes()
    {
        List<DeviceType> list = await _deviceTypeRepository.GetListAsync();
        var result = list.Select(e => new
        {
            Label = e.Name,
            Value = e.Id
        });
        return Ok(result);
    }
    [HttpGet]
    [Route("api/get-device-type-by-department")]
    public async Task<IActionResult> GetDeviceTypeByDepartment()
    {
        try
        {
            var department = await _departmentRepository.GetAsync(_currentUserOrganization.DepartmentId.Value);
            var deviceTypes = department.GetDeviceTypes();
            return Ok(new { Status = 0, Success = true, Data = deviceTypes.Select(e => new { e.Id, e.Name }) });
        }
        catch (Exception ex)
        {
            return Ok(new { Success = false, Error = ex.Message });
        }
    }
    [HttpGet]
    [Route("api/get-device-type-options")]
    public async Task<IActionResult> GetDeviceTypeByStation()
    {
        try
        {
            IList<DeviceType> deviceTypes = [];
            if (!string.IsNullOrWhiteSpace(stationCode))
            {
                var station = await _stationRepository.GetAsync(e => e.Code == stationCode);
                deviceTypes = station.Devices.Select(e => e.DeviceType).ToList();
            }
            else
            {
                var department = await _departmentRepository.GetAsync(_currentUserOrganization.DepartmentId.Value);
                deviceTypes = department.GetDeviceTypes();
            }
            return Ok(new { Status = 0, Success = true, Data = deviceTypes.Select(e => new { e.Id, e.Name }) });
        }
        catch (Exception ex)
        {
            return Ok(new { Success = false, Error = ex.Message });
        }
    }
}
